package com.tongtech.system.service.impl;

import com.tongtech.common.core.constant.UserConstants;
import com.tongtech.common.core.exception.ServiceException;
import com.tongtech.common.core.text.Convert;
import com.tongtech.common.core.utils.SpringUtils;
import com.tongtech.common.core.utils.StringUtils;
import com.tongtech.common.core.utils.uuid.UUID;
import com.tongtech.common.datascope.annotation.DataScope;
import com.tongtech.system.domain.InformationCategory;
import com.tongtech.system.domain.vo.InformationCategoryTreeSelect;
import com.tongtech.system.mapper.InformationCategoryMapper;
import com.tongtech.system.service.IInformationCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 资讯分类管理 服务实现
 *
 * @author xingyc
 */
@Service
public class InformationCategoryServiceImpl implements IInformationCategoryService
{
    @Autowired
    private InformationCategoryMapper infoCategoryMapper;

    /**
     * 查询资讯分类管理数据
     *
     * @param infoCategory 资讯分类信息
     * @return 资讯分类信息集合
     */
    @Override
    @DataScope(deptAlias = "infoCategory")
    public List<InformationCategory> selectInformationCategoryList(InformationCategory infoCategory)
    {
        return infoCategoryMapper.selectInformationCategoryList(infoCategory);
    }

    /**
     * 查询资讯分类树结构信息
     *
     * @param infoCategory 资讯分类信息
     * @return 资讯分类树信息集合
     */
    @Override
    public List<InformationCategoryTreeSelect> selectInformationCategoryTreeList(InformationCategory infoCategory)
    {
        List<InformationCategory> infoCategorys = SpringUtils.getAopProxy(this).selectInformationCategoryList(infoCategory);
        return buildInformationCategoryTreeSelect(infoCategorys);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param infoCategorys 资讯分类列表
     * @return 树结构列表
     */
    @Override
    public List<InformationCategory> buildInformationCategoryTree(List<InformationCategory> infoCategorys)
    {
        List<InformationCategory> returnList = new ArrayList<InformationCategory>();
        List<Long> tempList = infoCategorys.stream().map(InformationCategory::getInfoCategoryId).collect(Collectors.toList());
        for (InformationCategory infoCategory : infoCategorys)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(infoCategory.getParentId()))
            {
                recursionFn(infoCategorys, infoCategory);
                returnList.add(infoCategory);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = infoCategorys;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param infoCategorys 资讯分类列表
     * @return 下拉树结构列表
     */
    @Override
    public List<InformationCategoryTreeSelect> buildInformationCategoryTreeSelect(List<InformationCategory> infoCategorys)
    {
        List<InformationCategory> deptTrees = buildInformationCategoryTree(infoCategorys);
        return deptTrees.stream().map(InformationCategoryTreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据资讯分类ID查询信息
     *
     * @param infoCategoryId 资讯分类ID
     * @return 资讯分类信息
     */
    @Override
    public InformationCategory selectInformationCategoryById(Long infoCategoryId)
    {
        return infoCategoryMapper.selectInformationCategoryById(infoCategoryId);
    }

    /**
     * 根据ID查询所有子资讯分类（正常状态）
     *
     * @param infoCategoryId 资讯分类ID
     * @return 子资讯分类数
     */
    @Override
    public int selectNormalChildrenInformationCategoryById(Long infoCategoryId)
    {
        return infoCategoryMapper.selectNormalChildrenInformationCategoryById(infoCategoryId);
    }

    /**
     * 是否存在子节点
     *
     * @param infoCategoryId 资讯分类ID
     * @return 结果
     */
    @Override
    public boolean hasChildByInformationCategoryId(Long infoCategoryId)
    {
        int result = infoCategoryMapper.hasChildByInformationCategoryId(infoCategoryId);
        return result > 0;
    }


    /**
     * 校验资讯分类名称是否唯一
     *
     * @param infoCategory 资讯分类信息
     * @return 结果
     */
    @Override
    public boolean checkInformationCategoryNameUnique(InformationCategory infoCategory)
    {
        Long deptId = StringUtils.isNull(infoCategory.getInfoCategoryId()) ? -1L : infoCategory.getInfoCategoryId();
        InformationCategory info = infoCategoryMapper.checkInformationCategoryNameUnique(infoCategory.getCategoryName(), infoCategory.getParentId());
        if (StringUtils.isNotNull(info) && info.getInfoCategoryId().longValue() != deptId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存资讯分类信息
     *
     * @param infoCategory 资讯分类信息
     * @return 结果
     */
    @Override
    public int insertInformationCategory(InformationCategory infoCategory)
    {
        InformationCategory info = infoCategoryMapper.selectInformationCategoryById(infoCategory.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new ServiceException("资讯分类停用，不允许新增");
        }
        infoCategory.setCategoryCode(UUID.fastUUID().toString().replace("-",""));
        infoCategory.setAncestors(info.getAncestors() + "," + infoCategory.getParentId());
        return infoCategoryMapper.insertInformationCategory(infoCategory);
    }

    /**
     * 修改保存资讯分类信息
     *
     * @param infoCategory 资讯分类信息
     * @return 结果
     */
    @Override
    public int updateInformationCategory(InformationCategory infoCategory)
    {
        InformationCategory newParentInformationCategory = infoCategoryMapper.selectInformationCategoryById(infoCategory.getParentId());
        InformationCategory oldInformationCategory = infoCategoryMapper.selectInformationCategoryById(infoCategory.getInfoCategoryId());
        if (StringUtils.isNotNull(newParentInformationCategory) && StringUtils.isNotNull(oldInformationCategory))
        {
            String newAncestors = newParentInformationCategory.getAncestors() + "," + newParentInformationCategory.getInfoCategoryId();
            String oldAncestors = oldInformationCategory.getAncestors();
            infoCategory.setAncestors(newAncestors);
            updateInformationCategoryChildren(infoCategory.getInfoCategoryId(), newAncestors, oldAncestors);
        }
        int result = infoCategoryMapper.updateInformationCategory(infoCategory);
        if (UserConstants.DEPT_NORMAL.equals(infoCategory.getStatus()) && StringUtils.isNotEmpty(infoCategory.getAncestors())
                && !StringUtils.equals("0", infoCategory.getAncestors()))
        {
            // 如果该资讯分类是启用状态，则启用该资讯分类的所有上级资讯分类
            updateParentInformationCategoryStatusNormal(infoCategory);
        }
        return result;
    }

    /**
     * 修改该资讯分类的父级资讯分类状态
     *
     * @param infoCategory 当前资讯分类
     */
    private void updateParentInformationCategoryStatusNormal(InformationCategory infoCategory)
    {
        String ancestors = infoCategory.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        infoCategoryMapper.updateInformationCategoryStatusNormal(deptIds);
    }

    /**
     * 修改子元素关系
     *
     * @param infoCategoryId 被修改的资讯分类ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateInformationCategoryChildren(Long infoCategoryId, String newAncestors, String oldAncestors)
    {
        List<InformationCategory> children = infoCategoryMapper.selectChildrenInformationCategoryById(infoCategoryId);
        for (InformationCategory child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            infoCategoryMapper.updateInformationCategoryChildren(children);
        }
    }

    /**
     * 删除资讯分类管理信息
     *
     * @param deptId 资讯分类ID
     * @return 结果
     */
    @Override
    public int deleteInformationCategoryById(Long deptId)
    {
        return infoCategoryMapper.deleteInformationCategoryById(deptId);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<InformationCategory> list, InformationCategory t)
    {
        // 得到子节点列表
        List<InformationCategory> childList = getChildList(list, t);
        t.setChildren(childList);
        for (InformationCategory tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<InformationCategory> getChildList(List<InformationCategory> list, InformationCategory t)
    {
        List<InformationCategory> tlist = new ArrayList<InformationCategory>();
        Iterator<InformationCategory> it = list.iterator();
        while (it.hasNext())
        {
            InformationCategory n = (InformationCategory) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getInfoCategoryId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<InformationCategory> list, InformationCategory t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
